// 导入路由对象构造函数
const Router = require("koa-router");
const http = require("../utils/http.js");

// 创建路由导航
const router = new Router({
  prefix: "/order"
});

// 自定义配置路由对象
function formatOrderList(list) {
  let result = [];
  list.forEach(item => {
    let {
      order_id,
      pid,
      count,
      price,
      name,
      avatar,
      brief
    } = item;
    let detailItem = {
      pid,
      count,
      price,
      name,
      avatar,
      brief
    };
    let target = result.find(item2 => item2.order_id === order_id);
    if (target) {
      target.details.push(detailItem);
    } else {
      let {
        account,
        order_time,
        is_pay
      } = item;
      let {
        address_id,
        receive_name,
        receive_phone,
        receive_region,
        receive_detail,
        is_default
      } = item;
      let address = {
        address_id,
        receive_name,
        receive_phone,
        receive_region,
        receive_detail,
        is_default
      };
      result.push({
        order_id,
        account,
        order_time,
        is_pay,
        address,
        details: [detailItem]
      });
    }
  });
  return result;
}
// 新增订单
router.post('/add', async (ctx, next) => {
  const openid = ctx.state.openid;
  const {
    ids,
    account,
    address_id
  } = ctx.request.body;
  let sql = "call p_orderConfirm(?,?,?,?,?);";
  let date = new Date();
  let order_time = `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
  const results = await http(sql, [ids.join(","), account, order_time, openid, address_id]);
  return Promise.resolve(results[0][0].order_time);
});
// 根据订单编号查询订单的详细信息
router.get('/model/:id', async (ctx, next) => {
  const order_id = ctx.params.id;
  let sql = "select * from `v_order_address_product` where `order_id` = ?;";
  const results = await http(sql, [order_id]);
  return Promise.resolve(formatOrderList(results));
});
// 订单付款
router.get('/pay/:id', async (ctx, next) => {
  const id = ctx.params.id;
  const sql = "update `dt_order` set `is_pay` = 1 where `id` = ?;";
  const results = await http(sql, [id]);
  return Promise.resolve();
});
// 查询订单
router.get('/list/:flag', async (ctx, next) => {
  const openid = ctx.state.openid;
  const flag = ctx.params.flag; // flag有3个值，1：全部订单，2：付款订单，3：未付款订单
  let sql = "";
  switch (flag) {
    case "2":
      sql = "select * from `v_order_address_product` where `openid` = ? and `is_pay` = 1;";
      break;
    case "3":
      sql = "select * from `v_order_address_product` where `openid` = ? and `is_pay` = 0;";
      break;
    case "1":
    default:
      sql = "select * from `v_order_address_product` where `openid` = ?;";
      break;
  }
  const results = await http(sql, [openid]);
  return Promise.resolve(formatOrderList(results));
});
// 删除订单

module.exports = router.routes();